import { useReducer } from "react"

const reducer=(state,action)=>{
    switch(action.type){
        case'add':
        const todo={id:action.payload.id,text:action.payload.text,completed:false}
        return{...state,todos:[...state.todos,todo]}
        case'remove':
        return {...state,todos:state.todos.filter(todo=>todo.id!==action.payload)}
        case'toggle':
        const todoIndex=state.todos.findIndex(todo=>todo.id===action.payload)
        const newTodo={...state.todos[todoIndex],completed:!state.todos[todoIndex].completed}
        return{...state,todos:[
            ...state.todos.slice(0,todoIndex),
            newTodo,
            ...state.todos.slice(0,todoIndex+1)
        ]}
        case 'filter':
            return {...state,filter:action.payload}
        default:
         return state
    }
}

const initState={
    todos:[
        {id:1,text:'abc',completed:true},
        {id:2,text:'cmd',completed:false},

    ]
}

const makeId=()=>Math.random().toString(36).substr(-8)

const List=()=>{
    const [state,dispatch]=useReducer(reducer,initState)
    const  visibleTodos =state.todos.filter(todo=>{
        switch(state.filter){
         case'completed':
         return todo.completed
         case'action':
         return !todo.completed
         default:
            return todo
        }
       
    })
    return(
        <div>   
         <form onSubmit={(e)=>{
        e.preventDefault()
        const text=e.target.text.value.trim()
        e.target.text.focus()
        if(text.length>0){
        dispatch({type:'add',payload:{id:makeId(),text}})}
         }}>
             <input type='text'  name='text' />
             <button>添加</button>
         </form>
         <ul>
                 {visibleTodos.map(todo=><li key={todo.id}>
                     <span style={{textDecoration:todo.completed ?'line-through':'none'}}>
                     {todo.text}
                     </span>

                     <button onClick={()=>{dispatch({type:'remove',payload:todo.id})}}>删除</button>
                 </li>)}
             </ul>
             <div>
                 <span onClick={()=>{dispatch({type:'filter',payload:'all'})}} style={{color:state.filter==='all'?'red':'blue'}}>全部</span>
                 <span onClick={()=>{dispatch({type:'filter',payload:'completed'})}} style={{color:state.filter==='completed'?'red':'blue'}}>已完成</span>
                 <span onClick={()=>{dispatch({type:'filter',payload:'action'})}} style={{color:state.filter==='action'?'red':'blue'}}>未完成</span>

             </div>
        </div>
    )
}
export default List